package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.ListNode;
import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

class SplitLinkedListInParts {
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode[] splitListToParts(ListNode head, int k) {
            ListNode[] ans = new ListNode[k];
            ListNode index = head;
            int size = 0;
            while (head != null) {
                size++;
                head = head.next;
            }
            int part = size / k;
            int extra = size % k;
            if (part < 1) {
                for (int i = 0; i < k; i++) {
                    if (index == null) {
                        ans[i] = null;
                    } else {
                        ListNode temp = index;
                        index = index.next;
                        temp.next = null;
                        ans[i] = temp;
                    }

                }
            } else {
                for (int i = 0; i < k; i++) {
                    int range = 1;
                    int partOne = part;
                    partOne = extra > 0 ? partOne + 1 : partOne;
                    ListNode temp = index;
                    while (range < partOne) {
                        index = index.next;
                        range++;
                    }
                    ListNode t = index;
                    index = index.next;
                    t.next = null;
                    ans[i] = temp;
                    extra--;
                }
            }
            return ans;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}